package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.mapper.AdvanceReceiptBillMapper;
import com.zhentao.mapper.MemberMapper;
import com.zhentao.mapper.SupplierMapper;
import com.zhentao.pojo.Member;
import com.zhentao.pojo.Supplier;
import com.zhentao.pojo.AdvanceReceiptBill;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.zhentao.service.AdvanceReceiptBillService;
import com.zhentao.util.ExcelExportUtil;

/**
 * 收预付款管理接口
 */
@RestController
@RequestMapping("/finance/advanceReceiptBill")
public class AdvanceReceiptBillController {

    @Autowired
    private AdvanceReceiptBillMapper advanceReceiptBillMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private AdvanceReceiptBillService advanceReceiptBillService;

    /**
     * 分页查询收预付款
     */
    @GetMapping("/list")
    public Result<Page<AdvanceReceiptBill>> list(
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
            AdvanceReceiptBill query) {
        Page<AdvanceReceiptBill> page = new Page<>(pageNum, pageSize);
        QueryWrapper<AdvanceReceiptBill> wrapper = new QueryWrapper<>();
        
        if (query != null) {
            if (query.getStatus() != null) {
                wrapper.eq("status", query.getStatus());
            }
            if (query.getMemberId() != null) {
                wrapper.eq("member_id", query.getMemberId());
            }
            if (query.getSupplierId() != null) {
                wrapper.eq("supplier_id", query.getSupplierId());
            }
            if (StringUtils.hasText(query.getBillNo())) {
                wrapper.like("bill_no", query.getBillNo());
            }
            if (query.getTenantId() != null) {
                wrapper.eq("tenant_id", query.getTenantId());
            }
        }
        wrapper.orderByDesc("create_time");
        
        Page<AdvanceReceiptBill> resultPage = advanceReceiptBillMapper.selectPage(page, wrapper);
        // 填充显示字段：customerName / supplierName
        for (AdvanceReceiptBill bill : resultPage.getRecords()) {
            if (bill.getMemberId() != null) {
                Member m = memberMapper.selectById(bill.getMemberId());
                if (m != null) bill.setCustomerName(m.getName());
            }
            if (bill.getSupplierId() != null) {
                Supplier s = supplierMapper.selectById(bill.getSupplierId());
                if (s != null) bill.setSupplierName(s.getName());
            }
        }
        return Result.success(resultPage);
    }

    /**
     * 获取收预付款详情
     */
    @GetMapping("/detail/{id}")
    public Result<AdvanceReceiptBill> getDetail(@PathVariable Long id) {
        return Result.success(advanceReceiptBillMapper.selectById(id));
    }

    /**
     * 新增收预付款
     */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody AdvanceReceiptBill advanceReceiptBill) {
        if (advanceReceiptBill.getCreateTime() == null) {
            advanceReceiptBill.setCreateTime(new Date());
        }
        if (advanceReceiptBill.getStatus() == null) {
            advanceReceiptBill.setStatus(0); // 0-草稿
        }
        if (advanceReceiptBill.getTenantId() == null) {
            advanceReceiptBill.setTenantId(1L);
        }
        advanceReceiptBillMapper.insert(advanceReceiptBill);
        return Result.success();
    }

    /**
     * 修改收预付款
     */
    @PutMapping("/update")
    public Result<Void> update(@RequestBody AdvanceReceiptBill advanceReceiptBill) {
        advanceReceiptBillMapper.updateById(advanceReceiptBill);
        return Result.success();
    }

    /**
     * 删除收预付款
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        advanceReceiptBillMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除收预付款
     */
    @DeleteMapping("/batchDelete")
    public Result<Void> batchDelete(@RequestBody java.util.List<Long> ids) {
        advanceReceiptBillMapper.deleteBatchIds(ids);
        return Result.success();
    }

    /**
     * 审核收预付款
     */
    @PutMapping("/approve/{id}")
    public Result<Void> approve(@PathVariable Long id) {
        AdvanceReceiptBill advanceReceiptBill = advanceReceiptBillMapper.selectById(id);
        if (advanceReceiptBill != null) {
            advanceReceiptBill.setStatus(1); // 1-已审核
            advanceReceiptBillMapper.updateById(advanceReceiptBill);
        }
        return Result.success();
    }

    /**
     * 批量审核收预付款
     */
    @PutMapping("/batchApprove")
    public Result<Void> batchApprove(@RequestBody java.util.List<Long> ids) {
        for (Long id : ids) {
            AdvanceReceiptBill advanceReceiptBill = advanceReceiptBillMapper.selectById(id);
            if (advanceReceiptBill != null) {
                advanceReceiptBill.setStatus(1); // 1-已审核
                advanceReceiptBillMapper.updateById(advanceReceiptBill);
            }
        }
        return Result.success();
    }

    /**
     * 获取收预付款统计
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getStats(AdvanceReceiptBill query) {
        Map<String, Object> stats = new HashMap<>();
        QueryWrapper<AdvanceReceiptBill> wrapper = new QueryWrapper<>();
        
        if (query != null) {
            if (query.getStatus() != null) {
                wrapper.eq("status", query.getStatus());
            }
            if (query.getMemberId() != null) {
                wrapper.eq("member_id", query.getMemberId());
            }
            if (query.getTenantId() != null) {
                wrapper.eq("tenant_id", query.getTenantId());
            }
        }
        
        wrapper.select("IFNULL(SUM(amount), 0) as total_amount");
        Map<String, Object> totalMap = advanceReceiptBillMapper.selectMaps(wrapper).get(0);
        BigDecimal totalAmount = new BigDecimal(totalMap.get("total_amount").toString());
        stats.put("totalAmount", totalAmount);
        
        QueryWrapper<AdvanceReceiptBill> countWrapper = new QueryWrapper<>();
        if (query != null) {
            if (query.getStatus() != null) {
                countWrapper.eq("status", query.getStatus());
            }
            if (query.getMemberId() != null) {
                countWrapper.eq("member_id", query.getMemberId());
            }
            if (query.getTenantId() != null) {
                countWrapper.eq("tenant_id", query.getTenantId());
            }
        }
        Long count = advanceReceiptBillMapper.selectCount(countWrapper);
        stats.put("totalCount", count);
        
        return Result.success(stats);
    }

    /**
     * 导出预收付款数据
     */
    @GetMapping("/export")
    public void export(AdvanceReceiptBill query, HttpServletResponse response) throws IOException {
        try {
            QueryWrapper<AdvanceReceiptBill> wrapper = new QueryWrapper<>();
            
            if (query != null) {
                if (query.getStatus() != null) {
                    wrapper.eq("status", query.getStatus());
                }
                if (query.getMemberId() != null) {
                    wrapper.eq("member_id", query.getMemberId());
                }
                if (query.getTenantId() != null) {
                    wrapper.eq("tenant_id", query.getTenantId());
                }
            }
            wrapper.orderByDesc("create_time");
            
            // 查询所有数据
            List<AdvanceReceiptBill> advanceReceiptBills = advanceReceiptBillService.list(wrapper);
            
            // 准备Excel数据
            List<String> headers = new ArrayList<>();
            headers.add("单据编号");
            headers.add("会员ID");
            headers.add("金额");
            headers.add("状态");
            headers.add("创建时间");
            
            List<List<Object>> dataList = new ArrayList<>();
            for (AdvanceReceiptBill bill : advanceReceiptBills) {
                List<Object> row = new ArrayList<>();
                row.add(bill.getBillNo() != null ? bill.getBillNo() : "");
                row.add(bill.getMemberId() != null ? bill.getMemberId().toString() : "");
                row.add(bill.getAmount() != null ? bill.getAmount().toString() : "0.00");
                row.add(getStatusText(bill.getStatus()));
                row.add(bill.getCreateTime() != null ? bill.getCreateTime().toString() : "");
                dataList.add(row);
            }
            
            // 导出Excel
            String fileName = "预收付款数据_" + java.time.LocalDate.now();
            ExcelExportUtil.exportToResponse(response, fileName, headers, dataList);
            
        } catch (Exception e) {
            // 如果导出失败，返回错误信息
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待审核";
            case 1: return "已审核";
            case 2: return "已拒绝";
            default: return "未知";
        }
    }
}
